<script setup>
// import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
// import SysDep from '@/views/SystemManage/SysDep/SysDep.vue'
import PickCoords from '@/components/PickCoords/PickCoords.vue'
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.landId ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  pickDate: [],
  landName: '',
  landNature: '',
  landAddress: '',
  landArea: 0,
  isContract: 2,
  landAttribute: '',
  plantType: '',
  deptId: '',
  remark: '',
  positionImg: '',
  positionList: []
})
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.landId && show.value) {
      const { resultObject } = await api.getMassifInfo({ id: props.curRow.landId })
      resObj = resultObject
      formData.value = {
        ...formData.value,
        ...val,
        ...resObj,
        pickDate: [resObj.startDate, resObj.endDate]
      }
    } else {
      formData.value = {
        pickDate: [],
        landName: '',
        landNature: '',
        landAddress: '',
        landArea: 0,
        isContract: 2,
        landAttribute: '',
        plantType: '',
        deptId: '',
        remark: '',
        positionImg: '',
        positionList: []
      }
    }
  },
  { deep: true, immediate: true }
)
// 是否显示弹窗
const show = ref(false)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      pickDate: [],
      landName: '',
      landNature: '',
      landAddress: '',
      landArea: 0,
      isContract: 2,
      landAttribute: '',
      plantType: '',
      deptId: '',
      remark: '',
      positionImg: '',
      positionList: []
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  submitLoading.value = true
  let params = {
    ...formData.value,
    ...info,
    startDate: formData.value?.pickDate?.[0] || '',
    endDate: formData.value?.pickDate?.[1] || ''
  }
  await api
    .editMassif(params)
    .then(() => {
      message.success('编辑成功')
      show.value = false
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
      emits('reload')
    })
    .catch(() => {
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
    })
}
// 新增数据
const addItem = async (info) => {
  submitLoading.value = true
  let params = {
    ...formData.value,
    ...info,
    startDate: formData.value?.pickDate?.[0] || '',
    endDate: formData.value?.pickDate?.[1] || ''
  }
  await api
    .addMassif(params)
    .then(() => {
      message.success('新增成功')
      show.value = false
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
      emits('reload')
    })
    .catch(() => {
      setTimeout(() => {
        submitLoading.value = false
      }, 30)
    })
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.landId) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })

const getImage = (e) => {
  formData.value.positionImg = e
}
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="地块性质"
        name="landNature"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.landNature"
          :options="getOptions('land_nature')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        label="地块名称"
        name="landName"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.landName" allowClear />
      </a-form-item>
      <a-form-item
        label="地块面积(亩)"
        name="landArea"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.landArea" allowClear />
      </a-form-item>
      <a-form-item
        label="地块位置"
        name="landAddress"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.landAddress" allowClear />
      </a-form-item>
      <a-form-item
        label="地块绘制"
        name="positionList"
        :rules="[{ required: true, message: '请绘制' }]"
      >
        <a-form-item-rest>
          <PickCoords v-model="formData.positionList" @getImage="getImage" />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="地块属性"
        name="landAttribute"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.landAttribute"
          :options="getOptions('land_attribute')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        label="种植作物类型"
        name="plantType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.plantType"
          :options="getOptions('plant_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item label="是否被承包" name="isContract" required>
        <a-switch
          v-model:checked="formData.isContract"
          checked-children="是"
          un-checked-children="否"
          :checkedValue="1"
          :unCheckedValue="2"
        />
      </a-form-item>
      <a-form-item
        :label="`${formData.isContract === 1 ? '承包' : '归属'}人`"
        name="person"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.person" allowClear />
      </a-form-item>
      <a-form-item
        :label="`${formData.isContract === 1 ? '承包' : '归属'}人联系方式`"
        name="personPhone"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.personPhone" allowClear />
      </a-form-item>
      <a-form-item
        :label="`${formData.isContract === 1 ? '承包' : '归属'}时间`"
        extra="注：未填写默认永久"
        name="pickDate"
      >
        <a-range-picker
          v-model:value="formData.pickDate"
          valueFormat="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <!-- <a-form-item label="选择合作社" name="deptId" :rules="[{ required: true, message: '请输入' }]">
        <a-form-item-rest>
          <SltFromTable v-model="formData.deptId" :component="SysDep" :fieldNames="{ name: 'name', id: 'id' }"
            :nameValue="formData.deptName" />
        </a-form-item-rest>
      </a-form-item> -->
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formData.remark" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>